package io.summer.basis.func;

import cn.hutool.core.util.StrUtil;
import io.summer.basis.tool.LambdaTool;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.function.Function;

/**
 * Serializable function
 *
 * @author ml
 */
@FunctionalInterface
public interface SFunction<T, R> extends Function<T, R>, Serializable {
  String GET = "get";

  /**
   * 获取原始名(raw)
   *
   * @param sf function
   * @return getter name
   */
  static <T, R> String r(SFunction<T, R> sf) {
    try {
      String name = LambdaTool.getSerializedLambda(sf).getImplMethodName();
      if (name.startsWith(GET)) {
        return StrUtil.lowerFirst(name.substring(GET.length()));
      } else {
        return name;
      }
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) {
    }
    return "";
  }

  /**
   * 获取下划线分割的形式(underscore)
   *
   * @param sf function
   * @return getter name
   */
  static <T, R> String u(SFunction<T, R> sf) {
    return StrUtil.toUnderlineCase(r(sf));
  }
}
